<template>
  <div>
    <Card dis-hover :padding="searchPadding" v-if="showSearch">
      <!-- <table-search
        :placeholder="searchPlaceholder"
        :showAdvanced="showAdvanced"
        @on-table-search="handleSearch"
      >
        <Button
          v-if="!customSearchButtons"
          type="primary"
          icon="ios-add"
          @click.stop="handleOpenCreate"
        >新建</Button>
        <template slot="advanced-search-form">
          <slot name="advanced-search"></slot>
        </template>
        <slot name="search-button"></slot>
      </table-search>-->
      <div class="search-con search-con-top">
        <Input
          clearable
          v-if="!customSearchInput"
          :placeholder="placeholder"
          @on-enter="handleSearch"
          class="search-input"
          v-model="searchValue"
        />
        <slot name="search-input"></slot>
        <Button @click.stop="handleSearch" class="search-btn" icon="ios-search" type="primary">搜索</Button>
        <Button @click.stop="handleClearFilter" class="search-btn">清空</Button>
        <div style="float: right;">
          <Button
            v-if="!customSearchButtons"
            type="primary"
            icon="ios-add"
            @click.stop="handleOpenCreate"
          >新建</Button>
          <slot name="search-button"></slot>
        </div>
      </div>
    </Card>

    <table-tool
      :style="toolStyles"
      :top="toolTop"
      :select-num="selectNum"
      @on-close-tool="handleCloseTool"
    >
      <tool-item v-if="!customTools" @on-click="handleOpenUpdate" iconType="md-create" name="修改"></tool-item>
      <tool-item v-if="!customTools" @on-click="handleDelete" iconType="md-trash" name="删除"></tool-item>
      <tool-item
        v-for="(tool,index) in extendTools"
        :key="index"
        @on-click="handleToolEvent(tool)"
        :iconType="tool.iconType"
        :name="tool.name"
      ></tool-item>
      <slot name="tool-items"></slot>
    </table-tool>

    <custom-filter
      style="margin-top: 7px;min-height:38px"
      v-if="showFilter"
      @on-delete-filter="handleDeleteFilter"
      @on-save-filter="handleSaveFilter"
      :filters="filters"
      :fields="filterFields"
      :select-filter-id="selectFilterId"
      @on-click-filter="handleClickFilter"
    ></custom-filter>

    <xinya-table
      :loading="loadingShow"
      :virtual-scroller="virtualScroller"
      @on-load-more="onLoadMore"
      :item-height="itemHeight"
      :height="tableHeight"
      stripe
      border
      :width="tableWidth"
      ref="tables"
      :data="tableData"
      :columns="columns"
      :show-column-setting="showColumnSetting"
      :form-columns="columnFields"
      @on-sort-change="onSortChange"
      @on-row-click="onRowClick"
      @on-row-dblclick="dbClick"
      @on-select="onSelect"
      @on-select-cancel="onSelectCancel"
      @on-select-all="onSelectAll"
      @on-selection-change="onSelectionChange"
      @header-dragend="handleHeaderDragend"
      @on-save-column-setting="handleCustomViewConfirm"
      @on-cell-click="handleCellClick"
      @on-link-click="handleLinkClick"
    ></xinya-table>

    <div style="margin-top: 10px;height: 37px;" v-if="!virtualScroller">
      <Page
        ref="tablepage"
        style="float: right"
        :total="total"
        show-total
        show-sizer
        show-elevator
        :current.sync="tablePage"
        :page-size="perPage"
        :page-size-opts="pageSizeOpts"
        @on-change="handlePageChange"
        @on-page-size-change="handlePageSizeChange"
      />
    </div>
    <Modal
      v-model="createVisible"
      :draggable="modalDraggable"
      :width="modalWidth"
      :loading="modalLoading"
      :title="modalTitle"
      @on-ok="onFormSave"
      @on-cancel="onFormCancel"
    >
      <div class="innerbox" :style="modalHeight">
        <xy-form ref="forms" :form-json="cloneFormData" :option="formOption"></xy-form>
      </div>
    </Modal>
    <slot></slot>
  </div>
</template>

<script>
import { mapActions } from "vuex";
import { on, off } from "@/libs/tools";
import Emitter from "@/mixins/emitter";

import "./index.less";
import formMinxin from "./mixins/form.js";
import filtersMinxin from "./mixins/filters.js";
import { deepCopy } from "@/libs/util";

export default {
  name: "Tables",
  components: {},
  mixins: [formMinxin, filtersMinxin, Emitter],
  props: {
    // 是否显示搜索栏
    showSearch: {
      type: Boolean,
      default: true
    },
    // 更多检索条件
    showAdvanced: {
      type: Boolean,
      default: true
    },
    // 是否启用无限滚动加载
    virtualScroller: {
      type: Boolean,
      default: false
    },
    // 自定义工具栏
    customTools: {
      type: Boolean,
      default: false
    },
    // 自定义搜索栏按钮组
    customSearchButtons: {
      type: Boolean,
      default: false
    },
    // 工具栏扩展
    extendTools: {
      type: Array,
      default() {
        return [];
      }
    },
    // 搜索栏Placeholder
    searchPlaceholder: {
      type: String
    },
    // 搜索栏扩展
    extendSearchButtons: {
      type: Array,
      default() {
        return [];
      }
    },
    // 自定义搜索
    customSearchInput: {
      type: Boolean,
      default: false
    },
    // 隐藏复选框
    hideChecked: {
      type: Boolean,
      default: false
    },
    filterMethod: Function
  },
  data() {
    return {
      loadingShow: false, // 加载数据
      showColumnSetting: false,
      tableData: [], // 表格数据

      itemHeight: 38, // 行高
      searchPadding: 10, // 搜索栏padding属性

      toolTop: 111, // 工具栏top属性
      selectNum: 0, // 工具栏selectNum属性
      columns: [], // 显示列

      total: 0, // 数据总数
      tablePage: 1, // 当前页码
      perPage: 20, // 每页条数
      tableHeight: this.makeTableHeight(), // 表格高度
      tableWidth: 0,
      pageSizeOpts: [10, 20, 30], // 每页条数切换的配置

      sort: [], // 排序数组
      keywords: {}, // 关键字查询

      menuData: {},
      selectRow: {},
      formOption: {
        // 显示表单重置按钮
        resetBtn: false,
        submitBtn: false,
        // 表单提交事件
        onSubmit: function(formData) {}
      },
      collapsed: true,
      searchConditions: []
    };
  },
  computed: {
    spinStyle() {
      return { height: `${this.tableHeight}px` };
    },
    toolStyles() {
      return {
        width: this.collapsed ? "calc(100% - 268px)" : "calc(100% - 77px)",
        left: this.collapsed ? "263px" : "72px",
        border: "none",
        "z-index": 1000
      };
    }
  },
  methods: {
    ...mapActions([
      "getForm",
      "getColumns",
      "updateColumns",
      "getFilters",
      "getTableData",
      "createFormData",
      "updateFormData",
      "deleteFormData",
      "deletesFormData",
      "updateFilters",
      "deleteFilters",
      "addFilters",
      "getFormDetail"
    ]),
    // 工具栏扩展事件
    handleToolEvent(tool) {
      const selectRows = this.$refs.tables.getSelection();
      this.$emit("on-tool-event", tool, selectRows);
    },
    makeTableHeight() {
      let tableHeight = window.innerHeight - 223;
      const mh = window.innerHeight - this.modalOutHeight;

      this.$nextTick(() => {
        this.modalHeight = {
          height: (mh < 250 ? 250 : mh) + "px"
        };
      });

      if (!this.virtualScroller) {
        tableHeight -= 43;
      }
      if (!this.showFilter) {
        tableHeight += 43;
      }
      return tableHeight;
    },
    makeTableWidth() {
      const winWidth = document.documentElement.clientWidth - 256;
      return this.collapsed ? winWidth : winWidth;
    },
    handleCellClick(info, columnInfo) {
      this.$emit("on-cell-click", info, columnInfo);
    },
    refreshPage() {
      this.tablePage = 1;
    },
    handlePageChange: function(page) {
      this.tablePage = page;
      this.refreshSelectedNum();
      this.getData();
    },
    handlePageSizeChange: function(pageSize) {
      this.perPage = pageSize;
      this.getData();
    },
    handleCloseTool: function() {
      this.$refs.tables.selectAll(false);
    },
    onLoadMore: function() {},
    dbClick: function() {},
    onRowClick(rowData, rowIndex) {
      if (!this.hideChecked) {
        this.$refs.tables.toggleSelect(rowIndex);
      }
    },
    onSelect: function() {},
    onSelectCancel: function() {},
    onSelectAll: function() {},
    handleLinkClick: function(params) {
      // this.getFormDetail({ form_id: this.formId, id: params.row.id });
      this.$emit("on-link-click", params);
    },
    onSelectionChange(selection) {
      this.$emit("on-selection-change", selection);
      this.selectNum = selection.length;
    },
    // 列表排序， 表格暂时不支持多列排序 TODO
    onSortChange(sort) {
      /*
       * if (sort.order === "normal") {
       *   this.sort = this.sort.filter(s => s.field_name !== sort.key);
       * } else {
       *   let sortIndx = this.sort.findIndex(s => s.field_name === sort.key);
       *   if (sortIndx != -1) {
       *     this.sort[sortIndx] = {field_name:sort.key,direction:sort.order};
       *   } else {
       *     this.sort.push({field_name:sort.key,direction:sort.order});
       *   }
       * }
       */
      if (sort.order === "normal") {
        this.sort = [];
      } else {
        this.sort = { field_name: sort.key, direction: sort.order };
      }

      this.refreshDate();
    },
    // 列宽拖动事件
    handleHeaderDragend: function(newWidth, oldWidth, column) {

      const columns = deepCopy(this.columns)
        .filter(c => c.field_type)
        .map(c => {
          if (c.field_id === column.field_id) {
            c.width = Number(newWidth);
          }
          return c;
        });
      this.updateColumns({
        form_id: this.formId,
        list: columns.map(c => {
          delete c.minWidth;
          delete c.type;
          delete c.align;
          return c;
        })
      });
    },
    // 搜索事件
    handleSearch: function(value) {
      /*
       * if (this.customSearchInput) {
       *   const filterMethod = this.filterMethod;
       *   this.searchConditions = filterMethod.call();
       * } else {
       *   const fieldNames = this.formData.ext
       *     ? this.formData.ext.keywords || []
       *     : [];
       *   this.keywords = { field_names: fieldNames, value };
       * }
       */

      this.refreshDate();
    },
    handleClearFilter() {
      this.$parent.handleClearFilter();
      // this.dispatch('formFieldsSetting', 'handleClearFilter', field);
    },
    refreshDate() {
      this.refreshSelectedNum();
      this.refreshPage();

      this.getData();
    },
    // 保存显示列设置
    handleCustomViewConfirm(columns) {
      this.updateColumns({
        form_id: this.formId,
        list: columns
          .filter(c => c.field_type)
          .map(c => {
            delete c.minWidth;
            delete c.type;
            delete c.align;
            return c;
          })
      }).then(res => {
        this.initColumnsData(true);
      });
    },
    refreshSelectedNum() {
      this.selectNum = 0;
    },
    handleResize(e) {
      this.tableHeight = this.makeTableHeight();
      this.tableWidth = this.makeTableWidth();
    },
    getData(filter) {
      const filterMethod = this.filterMethod;
      this.searchConditions = filterMethod.call();

      const filters = {
        form_id: this.formId,
        page_info: {
          page: this.tablePage,
          per_page: this.perPage
        },
        sort: this.sort
      };

      if (Object.keys(this.keywords).length > 0) {
        filters.keywords = this.keywords;
      }

      filters.conditions = this.filterConditions.concat(this.searchConditions);

      this.loadingShow = true;
      // 获取表格数据
      this.getTableData(filters).then(res => {
        this.tableData = res.list;

        this.total = res.total_count;
        this.loadingShow = false;
      });
    },

    initColumnsData(is_refresh = false) {
      // 获取显示字段
      this.getColumns({ form_id: this.formId, is_refresh }).then(data => {
        let columns = data.map(field => {
          field.editable = Number(field.editable);
          field.resizable = Number(field.resizable);
          field.sortable = Number(field.sortable);
          field.minWidth = 120;
          field.field_id = Number(field.field_id);

          const baseField = this.formData.fields.find(
            f => f.id == field.field_id
          );
          if (baseField.ext && baseField.ext.isLink) {
            field.type = "link";
          }

          return field;
        });
        if (!this.hideChecked) {
          columns = [
            {
              type: "selection",
              width: 60,
              align: "center"
            }
          ].concat(columns);
        }
        this.columns = columns;
      });
    },
    initTableData() {
      this.getFormData(() => {
        this.initColumnsData();
      });
      // 获取自定义检索条件
      this.initFiltersData();
      this.getData();
    },
    handleSiderChange() {
      this.collapsed = document.getElementsByClassName("collapsed").length == 0;
      // this.tableWidth = this.makeTableWidth();
      this.handleResize();
    }
  },
  created() {
    this.initTableData();
  },
  mounted() {
    on(window, "resize", this.handleResize);
    on(
      document.getElementsByClassName("js-sider")[0],
      "click",
      this.handleSiderChange
    );
    this.handleSiderChange();
  },
  watch: {
    formId: {
      handler() {
        this.initTableData();
      },
      deep: true
    }
  },
  beforeDestroy() {
    off(window, "resize", this.handleResize);
    off(
      document.getElementsByClassName("js-sider")[0],
      "click",
      this.handleSiderChange
    );
  }
};
</script>